package com.sk.bilibili.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.sk.bilibili.dto.QrCode;
import com.sk.bilibili.property.MinioProperty;
import com.sk.bilibili.property.QrProperty;
import lombok.SneakyThrows;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.nio.file.FileSystems;
import java.nio.file.Path;

/**
 * @author 邵康
 * @date 2021/11/23 13:09
 */
@Component
public class QrCodeUtils implements InitializingBean {

    @Autowired
    private QrProperty qrProperty;
    @Autowired
    private MinioProperty minioProperty;
    private QRCodeWriter qrCodeWriter;


    @SneakyThrows
    public QrCode generateQrCode(){
        String code = NameCreator.getName(qrProperty.getCodeLen());
        ByteArrayOutputStream os=new ByteArrayOutputStream();
        generate(String.format(qrProperty.getUrlPatten(),minioProperty.getBasePath(),code),os);
        String base64=Base64Utils.encode(os);
        return new QrCode(base64,code);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        qrCodeWriter = new QRCodeWriter();
    }

    @SneakyThrows
    public void generate(String info, OutputStream os) {
        BitMatrix matrix = qrCodeWriter.encode(info, BarcodeFormat.QR_CODE,
                qrProperty.getWidth(), qrProperty.getHeight());
        MatrixToImageWriter.writeToStream(matrix,"jpg",os);
    }

}
